$(function(){
	var _id = parseInt($_GET['id'] ? $_GET['id'] : 0);
	/**
	 * @desc 商品信息
	 */
	var global_product = {
			'page': $_GET['page'] ? $_GET['page'] : undefined,//页码
			'pageSize' : $_GET['pageSize'] ? $_GET['pageSize'] : undefined, //页数
//			'vendor': undefined,//往来单位
			'starTime': undefined,//开始时间
			'endTime' : undefined,//截至时间
//			'name' : undefined,
	}
	var global_count = 1;
	var global_remove = [];
	var select_units;
	//时间
	dateSelFun($('#adjustment_date'));
	

	if(_id){
		initAdjustment();
	}
	/**
	 * @初始化页面
	 */
	function initAdjustment() {
		$('#confirm').show();
		$('#save').attr('data-id',parseInt(_id));
		$.get('get-adjustment-info', {'id' : _id}, function(data, status) {
			if(status =='success' && data.Ack =='Success'){
				var H = data.Body.head;
				if(H){
					$('#adjustment_no').val(H.adjustment_no);
					$('#adjustment_date').val(intToLocalDate(H.adjustment_date,1));
					$('#handle_man').val(H.handle_man);
					$('#remark').val(H.remark);
					$('#create_man').val(H.username).attr('data-id', H.create_man);
					$('#remark').val(H.remark);
					if(+H.confirm_flag){
						$('#save').attr('style','display:none');
						$('#confirm').removeClass().addClass('btn btn-warning btn-sm pull-right').attr('disabled','disabled');
					}
				}
				var D = data.Body.det;
				if(D){
					$('#stockList').find('tr').remove();
					var total_payamount = 0;
					for(var i in D){
						var tmp_units= '';
						var U = D[i].product_unit;
						tmp_units = '<select class="form-control units" disabled><option value="0" data-rate="0"> </option>';
						for(var j in U){
							tmp_units +='<option value="'+U[j].unit_id+'" data-rate="'+U[j].rate+'">'+U[j].unit_name+'</option>';
						}
						tmp_units +='</select>';
						
						$('<tr>'
							+'<td class="text-center" name="ids" data-id="'+D[i].adjustment_det_id+'" data-pid="'+D[i].product_id+'">'+global_count+'</td>'
							+'<td class="text-center"><a href="javascript:void(0)"class="stock-minus-tr" data-id="'+D[i].product_id+'"> <i class="fa fa-minus-circle" style="color:red;" ></i></a></td>'
							+'<td class="text-center" name="name" data-id="'+D[i].product_id+'"><input title="商品名称" readonly type="text" value="'+D[i].product_name+'"'
							+'class="product_name stock-input50"  style="height: 30px;width:80%"> <a class="search-btn search-product" title="搜索"'
							+'href="javascript:void(0)"><i class="fa fa-search"></i></a></td>'
							+'<td class="text-center" name="unit" style="width:8%;">'+tmp_units+'</td>'
							+'<td class="text-center" name="quantity"><input type="text" class="quantity" value="'+D[i].quantity+'"></td>'
							+'<td class="text-center" name="price"><input type="text"  placeholder="0.00" class="price" value="'+D[i].price+'" disabled></td>'
							+'<td class="text-center" name="adjustment_price"><input type="text" placeholder="0.00" class="adjustment_price" value="'+D[i].adjustment_price+'" ></td>'
							+'<td class="text-center" name="remark"><input type="text" style="width:100%;" value="'+D[i].remark+'"></td>'	
						   +'</tr>').appendTo('#stockList');
						$('#stockList').find('tr:last').find('[name="unit"] select').val(D[i].quantity_unit);
						global_count++;
					}
				}
			}
		});
	};
	
	/**
	 * @desc 选择商品
	 */
	$('#stockList').on('click','.search-product',function(){
		$('#productName').val('');
		global_product.page = 1;
		global_product.name = undefined;
		getProducts();
		
	})
	//过滤商品
	$('#searchProduct').on('click', function() {
		var _name = trim($('#productName').val());
		global_product.name = _name;
		getProducts();
		return;
	})
	
	/**
	 * @desc 查询商品
	 */
	function getProducts(pageInfo){
		if (pageInfo !== undefined) {
			global_product.page = pageInfo.page;
			global_product.pageSize = pageInfo.pageSize;
		}
		$('#product_list').find('tr').remove();
		var index = layer.load();
		 $.ajax({
             url: 'get-products',
             type: "GET",
             cache: true,
             data: global_product,
             dataType: "json",
             jsonp: "callback",
             global:false,
             success: function(data){
            	 layer.close(index);
            	 var P = data.Body.list;
					if(P && P.length){
						for(var i in P){
							var tmp_units = ''
							var U = P[i].product_unit;
							tmp_units = '<select class="form-control units"><option value="0" data-rate="0"> </option>';
							for(var j in U){
								tmp_units +='<option value="'+U[j].unit_id+'" data-rate="'+U[j].rate+'">'+U[j].unit_name+'</option>';
							}
							tmp_units +='</select>';
							$('<tr>'
							+'<td class="text-center">'+(+i+1)+'</td>'
							+'<td class="text-center id">'+P[i].product_id+'</td>'
							+'<td class="text-center name">'+P[i].product_name+'</td>'
							+'<td class="text-center sn">'+P[i].product_sn+'</td>'
							+'<td class="text-center quantity">'+P[i].quantity+'</td>'
							+'<td class="text-center unit" data-unit="'+P[i].quantity_unit+'" data-rela="'+P[i].unit_content+'">'+(P[i].unit_name == null ? '':P[i].unit_name)+'</td>'
							+'<td class="text-center"><a href="javascript:void(0)" class="product_select" data-unit="'+encodeURI(tmp_units)+'" data-price="'+P[i].price+'">选择</a></td>'
							+'</tr>').appendTo('#product_list');
			              
						}
						var pageInfo = data.Body.page;
			            if (typeof pageInfo !== 'undefined'){
			              	refreshPaginationNavBar2($('.paginationNavBar'), pageInfo.page, pageInfo.pageSize, data.Body.count, getProducts);
			            }
					}else {
						$('<tr><td colspan="5" class="text-center">没有数据</td></tr>').appendTo('#product_list');
						refreshPaginationNavBar2($('.paginationNavBar'), 1, 10, 1, getProducts);
					}
				$('#chooseProduct').modal('show');//选择商品窗口
             }
		 })
	}
	
	//添加商品
	$('#product_list').on('click','.product_select',function(){
		var tmp_units = decodeURI($(this).attr('data-unit'));
		var _price = +$(this).attr('data-price');
		var tr =$(this).closest('tr');
		var id = tr.find('.id').text();
		var name = tr.find('.name').text();
		var sn = tr.find('.sn').text();
		var quantity = tr.find('.quantity').text();
		var unit = tr.find('.unit').data('unit');
		if(!+unit){
			alertTips('warning','请在商品管理添加单位');
			return false;
		}
		var unit_name = tr.find('.unit').text();
		var unit_content = tr.find('.unit').attr('data-rela');
		
		if(global_count == 1){
			var pid = $('#stockList').find('.stock-minus-tr').data['id'];
			if(pid == undefined){
				//刚开始添加数据
				$('#stockList').find('tr:first').remove();
			} ;
		}
		var check_flag = 0;
		$('#stockList').find('[name="ids"]').each(function(ii,ele){
			if(id == $(ele).attr('data-pid')){
				check_flag = 1;
			}
		})
		if(check_flag){
			return;
		}
		
		$('<tr>'
		  +'<td class="text-center" name="ids" data-id="" data-pid="'+id+'">'+global_count+'</td>'
		  +'<td class="text-center"><a href="javascript:void(0)"class="stock-minus-tr" data-id="'+id+'"> <i class="fa fa-minus-circle" style="color:red;" ></i></a></td>'
		  +'<td class="text-center" name="name" data-id="'+id+'"><input title="商品名称" readonly type="text" value="'+name+'"'
		  +'class="product_name stock-input50"  style="height: 30px;width:80%"> <a class="search-btn search-product" title="搜索"'
		  +'href="javascript:void(0)"><i class="fa fa-search"></i></a></td>'
		  +'<td class="text-center" name="unit" style="width:8%;">'+tmp_units+'</td>'
		  +'<td class="text-center" name="quantity"><input type="text" class="quantity" value="'+quantity+'"></td>'
		  +'<td class="text-center" name="price"><input type="text"  placeholder="0.00" class="price" value="'+_price+'" disabled></td>'
		  +'<td class="text-center" name="adjustment_price"><input type="text" placeholder="0.00" class="adjustment_price"></td>'
		  +'<td class="text-center" name="remark"><input type="text" style="width:100%;"></td>'
		  +'</tr>').appendTo('#stockList');
		$('#stockList').find('tr:last').find('[name="unit"]').find('.units').val(unit);
		global_count++;
	});
	
	//删除数据
	$('#stockList').on('click','.stock-minus-tr',function(){
		var tmp_id = $(this).closest('td').prev('td').attr('data-id');
		if ($.inArray(tmp_id, global_remove) >= 0) {
			return false;
		}
		if(tmp_id){
			global_remove.push({'adjustment_det_id':tmp_id});
		}
		
		if(global_count == 1){
			return false;
		} else if(global_count == 2){
			//添加一条数据要删除数据 后插入一条空数据
			$('#stockList').find('tr:first').remove();
			global_count--;
			insertOrginHtml();
//			SumCheckAmount();
			return false;
		} else {
			var self = $(this);
			//判断当前要删除的行,下面是否还有记录
            var nextTr = self.parent().parent().next('tr');
            if(nextTr.length){
            	//存在下一行，清空当前行数据
                self.closest('tr').remove();
                // 序号重新排列
                var td = $('#stockList').find('tr').find('td:first');
                $.each(td, function(index, item) {
                    var item = $(item);
                    item.text(index+1);
                })
                global_count--;
//                SumCheckAmount();
                return false;
            } else{
            	//删除的为最后一行
                self.closest('tr').remove();
                global_count--;
//                SumCheckAmount();
                return false;
            }
		}
		
	});
	
	(function(){
		select_units = '<select title="单位" class="form-control unit">'
			+ '<option value="0">单位</option>'
			+ '<option value="6">个</option>'
			+ '<option value="5">支</option>'
			+ '<option value="4">包</option>'
			+ '<option value="2">斤</option>'
			+ '<option value="1">箱</option>' + '</select>';
	})();
	var insertOrginHtml = function(){
		$('<tr>'
				  +'<td class="text-center" name="ids" data-id="" data-pid="">'+global_count+'</td>'
				  +'<td class="text-center"><a href="javascript:void(0)"class="stock-minus-tr" data-id=""> <i class="fa fa-minus-circle" style="color:red;" ></i></a></td>'
				  +'<td class="text-center" name="name" data-id=""><input title="商品名称" readonly type="text" value=""'
				  +'class="product_name stock-input50"  style="height: 30px;width:80%"> <a class="search-btn search-product" title="搜索"'
				  +'href="javascript:void(0)"><i class="fa fa-search"></i></a></td>'
				  +'<td class="text-center" name="unit" style="width:8%;">'+select_units+'</td>'
				  +'<td class="text-center" name="quantity"><input type="text" class="quantity" value=""></td>'
				  +'<td class="text-center" name="price"><input type="text"  placeholder="0.00" class="price" value="" disabled></td>'
				  +'<td class="text-center" name="adjustment_price"><input type="text" placeholder="0.00" class="adjustment_price"></td>'
				  +'<td class="text-center" name="remark"><input type="text" style="width:100%;"></td>'
				  +'</tr>').appendTo('#stockList');
	}
	
	//名称提示
	$('#stockList').on('click','.product_name',function(){
		var name = $(this).val();
		if(name !=undefined){
			layer.tips(name, $(this), {
				  tips: [4, '#78BA32']
			});
		}
	});
	
	(function() {
		// 保存
		$('#save').on('click', function() {
			//单头
			var head = adjustment_header();
			if(!head){
				return false;
			}
			//明细
			var detail = adjustment_detail();
			if(!detail){
				return false;
			}
			
			var ii = layer.load();
			$.post('save-adjustment',{'head':head,'det':detail,'remove': global_remove,'id':_id}, function(data,status){
				setTimeout(function(){
					  layer.close(ii);
				}, 1000);
				if(status =='success'){
					if(data.Ack =='Success'){
						alertTips('success','保存成功');
						setTimeout(function() {
 							window.location.reload();
						}, 1000);
					}
				} else {
					alertShows('error','网络错误');
				}
			})
		});

	})();	

	var adjustment_header = function() {
		var no = $('#adjustment_no').val();
		var adjustment_date = $('#adjustment_date').val();
		if (adjustment_date.length == 0) {
			alertTips('warning', '请输入调整时间');
			return false;
		}
		var handle_man = $('#handle_man').val();
		if (!+handle_man) {
			alertTips('warning', '请选择调整人员');
			return false;
		}
		var remark = $('#remark').val();
		var create_man = $('#create_man').attr('data-id');
		var adjustment_head = {
			'adjustment_no' : no,
			'adjustment_date' : adjustment_date,
			'handle_man' : handle_man,
			'create_man' : create_man,
			'remark' : remark,
		};
		return adjustment_head;
	}
	
	//成本调整明细
	var adjustment_detail = function(){
		var product_det=[];
		var product_info = [];
		var _tr = $('#stockList').find('tr');
		var flag = 1;
		if(_tr.length == 1){
			var pid = _tr.first('tr').find('td[name="name"]').attr('data-id');
			if(pid ==''){
				alertTips('warning','请选择商品');
				return false;
			}
		}
		_tr.each(function(index,element){
			var tr = $(this);
			var quantity = tr.find('[name="quantity"] input').val();
			if(quantity == ''){
				quantity = 0;
			}
			var line_id = tr.find('[name="ids"]').attr('data-id');
			if(line_id == ''){
				line_id = 0;
			}
			var price = tr.find('[name="price"] input').val();
			var adjustment_price = tr.find('[name="adjustment_price"] input').val();
			if(adjustment_price == '' || adjustment_price == 0){
				if(!+adjustment_price){
					if(confirm("调后单价为0,是否继续？")){
						price = 0;
					} else {
						flag = 0;
						return false;
					}
				}
			}
			var unit = tr.find('[name="unit"] select').val();
			if(!+unit){
				alertTips('warning','单位不能为空');
				flag = 0;
				return false;
			}
			product_det = {
				'adjustment_det_id' : line_id,
				'product_id' : tr.find('[name="name"]').attr('data-id'),
				'quantity' : quantity,
				'quantity_unit' : tr.find('[name="unit"] select').val(),
				'remark' : tr.find('[name="remark"] input').val(),
				'price' : decimal(price,2),
				'adjustment_price' : decimal(adjustment_price,2),
			};
			product_info.push(product_det);
			product_det = [];
		});
		if(!flag){
			product_info = [];
			return false;
		}
		if(product_info.length == 0){
			alertTips('warning','请选择产品！');
			return false;
		}
		return product_info;
	}
	
	//编辑页面的确认
	$('#confirm').on('click',function(){
		//检查是否有确认权限
		$.get('check-confirm-adjustment',function(data,status){
			if(data.Error =='User authentication fails'){
				alertTips('error', '你没有操作权限，如要操作，请向管理员申请');
				return;
			}
			layer.confirm('点击确认调整单将无法编辑，是否确认?', function(index) {
				$.get('confirm-adjustment',{'id':_id},function(data,status){
					if(status =='success'){
						if(data.Ack =='Success'){
							alertTips('success','确认成功');
							setTimeout(function(){
								window.location.reload();
							},1000);
						}
					} else{
						alertTips('error','网络错误');
					}
				})
				layer.close(index);
			});
		})
	})
})